import { constantRoutes } from '@/router'
import { currentmenu } from '@/api/project/system/project_sys_sys_menu.js'
import Layout from '@/layout'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: [],
  routesMap: {}
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  },
  SET_ROUTESMAP:(state, routesMap) =>{
    state.routesMap = routesMap
  }
}
String.prototype.replaceAll = function(s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
}
const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      currentmenu().then(result=>{ 
        const asyncRoutes=[];
        const asyncRoutesMap = {};
        result.dataSingle.forEach(element => {
          var l1 ={
            path: element.router_path,
            component: Layout,
            // redirect: element.link_url,
            redirect: '/dashboard',
            alwaysShow: true,
            // name: 'm_'+element.id,
            name: element.router_path.replaceAll('/','a_'),
            meta: {
              title: element.menu_name,
              icon: element.iconCls,
              roles: [element.code]
            },
            children: []
          };
          if(element.children && element.children.length>0){
            element.children.forEach(son => { 
              const _link_url = son.link_url; 
              if(_link_url!=null && _link_url.length>0){ 
                const l2={
                  path: son.router_path,
                  code_aes: son.code_aes,
                  // name: 'm_'+son.id,
                  name: son.router_path.replaceAll('/','a_'),
                  meta: { title: son.menu_name, icon: son.iconCls,
                  roles: [son.code] },
                  hidden: son.menu_type==1?false:true
                }   
                if(_link_url.indexOf('@/views/project/system/')>=0){
                  l2.component = () => import(`@/views/project/system/${son.link_url.substring(23)}`)
                } 
                if(_link_url.indexOf('@/views/project/wmyw/')>=0){
                  l2.component = () => import(`@/views/project/wmyw/${son.link_url.substring(21)}`)
                } 
                if(_link_url.indexOf('@/views/project/wmyh/')>=0){
                  l2.component = () => import(`@/views/project/wmyh/${son.link_url.substring(21)}`)
                }
                l1.children.push(l2); 
                asyncRoutesMap[son.router_path] = l2;
              }
            });
          }
          asyncRoutes.push(l1);
        });
        let accessedRoutes 
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles) 
        commit('SET_ROUTES', accessedRoutes)
        commit('SET_ROUTESMAP', asyncRoutesMap)
        resolve(accessedRoutes)
      })
      .catch((result) => { 
        // alert('菜单权限错误');
        console.log(result.msg || result);
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
